<template>
    <el-row class="fire-ctl-info-form" type="flex" justify="center">
        <el-col>
            <div class="update-fire-ctl-category-wrap">
                <el-form ref="categoryForm" :model="categoryForm" :rules="categoryFormRules" @submit.native.prevent>
                    <el-form-item label="所属消防系统：" prop='fireSystemId' v-if="isParent">
                            <el-select v-model="categoryForm.fireSystemId" filterable 
                                placeholder="请选择"
                                @change="changeItem">
                                <el-option
                                    v-for="item in options"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                    </el-form-item>
                    <el-form-item label="名称：" prop='name'>
                            <el-input v-model="categoryForm.name" auto-complete="off" placeholder="请输入名称">
                            </el-input>
                    </el-form-item>
                    <el-form-item label="是否是模拟量：" prop='hasAnalog'>
                            <el-select v-model="categoryForm.hasAnalog" filterable 
                                placeholder="请选择"
                                @change="changeAnalog">
                                <el-option
                                    v-for="item in Analogs"
                                    :key="item.value"
                                    :label="item.name"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                    </el-form-item>
                    <el-form-item label="是否支持下发：" prop='isSupportSendDown'>
                            <el-switch v-model="categoryForm.isSupportSendDown" 
                                active-text="是" 
                                active-value="1"
                                inactive-text="否"
                                inactive-valu="0">
                            </el-switch>
                    </el-form-item>
                    <el-form-item label="属性是否关联子级：" prop='isRelationChild'>
                            <div>
                                <el-switch v-model="categoryForm.isRelationChild" 
                                active-text="是" 
                                active-value="1"
                                inactive-text="否"
                                inactive-valu="0">
                            </el-switch>
                            </div>
                    </el-form-item>
                    <el-form-item label="是否高危" prop='isHighRisk'>
                            <div>
                                <el-switch v-model="categoryForm.isHighRisk" 
                                active-text="是" 
                                active-value="1"
                                inactive-text="否"
                                inactive-valu="0">
                            </el-switch>
                            </div>
                    </el-form-item>
                    <el-form-item label="是否重点" prop='isKeyUnit'>
                            <div>
                                <el-switch v-model="categoryForm.isKeyUnit" 
                                active-text="是" 
                                active-value="1"
                                inactive-text="否"
                                inactive-valu="0">
                            </el-switch>
                            </div>
                    </el-form-item>
                    <el-form-item label="报警状态子名称：" prop='alarm_name'>
                            <el-input v-model="categoryForm.alarm_name" auto-complete="off" placeholder="请输入报警状态子名称"></el-input>
                    </el-form-item>
                    <el-form-item label="报警状态图片：">
                            <el-upload
                            :action="QINIUUPLOADURL"
                            :multiple="false"
                            ref="upload"
                            list-type="picture-card"
                            :data="qiniuData"
                            :on-success="function(res,file,fileList){return handleAvatarSuccess(res,file,fileList,1) }"
                            :on-remove="function(file,fileList){return handleRemovePic(file,fileList,1) }"
                            :on-error="handleError"
                            :before-upload="beforeAvatarUpload"
                            :on-preview="$imgPreview"
                            :file-list="alarmPicList"
                            accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="故障状态子名称：" prop='fault_name'>
                            <el-input v-model="categoryForm.fault_name" auto-complete="off" placeholder="请输入故障状态子名称"></el-input>
                    </el-form-item>
                    <el-form-item label="故障状态图片：">
                            <el-upload
                            :action="QINIUUPLOADURL"
                            :multiple="false"
                            ref="upload"
                            list-type="picture-card"
                            :data="qiniuData"
                            :on-success="function(res,file,fileList){return handleAvatarSuccess(res,file,fileList,2) }"
                            :on-remove="function(file,fileList){return handleRemovePic(file,fileList,2) }"
                            :on-error="handleError"
                            :before-upload="beforeAvatarUpload"
                            :on-preview="$imgPreview"
                            :file-list="faultPicList"
                            accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="屏蔽状态子名称：" prop='shield_name'>
                            <el-input v-model="categoryForm.shield_name" auto-complete="off" placeholder="请输入屏蔽状态子名称"></el-input>
                    </el-form-item>
                    <el-form-item label="屏蔽子状态图片：">
                            <el-upload
                            :action="QINIUUPLOADURL"
                            :multiple="false"
                            ref="upload"
                            list-type="picture-card"
                            :data="qiniuData"
                            :on-success="function(res,file,fileList){return handleAvatarSuccess(res,file,fileList,3) }"
                            :on-remove="function(file,fileList){return handleRemovePic(file,fileList,3) }"
                            :on-error="handleError"
                            :before-upload="beforeAvatarUpload"
                            :on-preview="$imgPreview"
                            :file-list="shieldPicList"
                            accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="联动状态子名称：" prop='linkage_name'>
                            <el-input v-model="categoryForm.linkage_name" auto-complete="off" placeholder="请输入联动状态子名称"></el-input>
                    </el-form-item>
                    <el-form-item label="联动子状态图片：">
                            <el-upload
                            :action="QINIUUPLOADURL"
                            :multiple="false"
                            ref="upload"
                            list-type="picture-card"
                            :data="qiniuData"
                            :on-success="function(res,file,fileList){return handleAvatarSuccess(res,file,fileList,4) }"
                            :on-remove="function(file,fileList){return handleRemovePic(file,fileList,4) }"
                            :on-error="handleError"
                            :before-upload="beforeAvatarUpload"
                            :on-preview="$imgPreview"
                            :file-list="linkagepicList"
                            accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="正常状态子名称：" prop="normal_name">
                            <el-input v-model="categoryForm.normal_name" auto-complete="off" placeholder="请输入正常状态子名称"></el-input>
                    </el-form-item>
                    <el-form-item label="正常子状态图片：">
                            <el-upload
                            :action="QINIUUPLOADURL"
                            :multiple="false"
                            ref="upload"
                            list-type="picture-card"
                            :data="qiniuData"
                            :on-success="function(res,file,fileList){return handleAvatarSuccess(res,file,fileList,5) }"
                            :on-remove="function(file,fileList){return handleRemovePic(file,fileList,5) }"
                            :on-error="handleError"
                            :before-upload="beforeAvatarUpload"
                            :on-preview="$imgPreview"
                            :file-list="normalPicList"
                            accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    
                    <el-form-item label="列表图片：">
                            <el-upload
                            :action="QINIUUPLOADURL"
                            :multiple="false"
                            ref="upload"
                            list-type="picture-card"
                            :data="qiniuData"
                            :on-success="function(res,file,fileList){return handleAvatarSuccess(res,file,fileList,6) }"
                            :on-remove="function(file,fileList){return handleRemovePic(file,fileList,6) }"
                            :on-error="handleError"
                            :before-upload="beforeAvatarUpload"
                            :on-preview="$imgPreview"
                            :file-list="listPicture"
                            accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>

                    <el-form-item label="详情图片：">
                            <el-upload
                            :action="QINIUUPLOADURL"
                            :multiple="false"
                            ref="upload"
                            list-type="picture-card"
                            :data="qiniuData"
                            :on-success="function(res,file,fileList){return handleAvatarSuccess(res,file,fileList,7) }"
                            :on-remove="function(file,fileList){return handleRemovePic(file,fileList,7) }"
                            :on-error="handleError"
                            :before-upload="beforeAvatarUpload"
                            :on-preview="$imgPreview"
                            :file-list="detailPicture"
                            accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    
                    <el-form-item label="备注：" prop='remarks'>
                            <el-input type="textarea" :rows="2" placeholder="请输入备注" 
                                v-model="categoryForm.remarks">
                            </el-input>
                    </el-form-item>
                    <el-form-item label-width="0" class="verifyidentity-button">
                        <el-button @click.stop="closeFun" round>取消</el-button>
                        <el-button type="primary" @click="saveCategoryInfo('categoryForm')" round>保存</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-col>
    </el-row>
</template>
<style lang="scss">
.fire-ctl-info-form {
    .el-switch__label--left{ 
        position: relative; 
        left: 46px; 
        color: #fff; 
        z-index: -1111; 
    } 
    .el-switch__label--right {
        position: relative; 
        right: 46px; 
        color: #fff; 
        z-index: -1111; 
    }
    .el-switch__label.is-active{ 
        z-index: 1111; 
        color: #fff; 
    }
    .el-switch__label--left{ 
        position: relative; 
        left: 46px; 
        color: #fff; 
        z-index: -1111; 
    }
    .el-switch__label--right{ 
        position: relative; 
        right: 46px; 
        color: #fff; 
        z-index: -1111; 
    } 
    .el-switch__label--right.is-active{ 
        z-index: 1111; 
        color: #fff !important; 
    }
    .el-switch__label--left.is-active{ 
        z-index: 1111; 
        color: #9c9c9c !important; 
    }
}
</style>
<script>
import { qnToken} from '@/api/api';
import util from '@/utils/util';
import { updateFireCtlCategory } from '@/api/sysConfig'

export default {
     name:'',
     props: {
         oldInfo: {},
         parentId:'',
         fireSystemId:'',
         closeFun: {
            type: Function,
            required: true,
        }
     },
     created() {
        var that = this;
        that.getToken();
        util.ilinkArrHandle.delDicArr_keyVal(55, function(arr){
            if (!that.oldInfo.id) {
               that.categoryForm.fireSystemId = arr[0].id;
            }
            that.options = arr;
        })
        if (that.parentId) {
          that.isParent = false;
        }
     
        if(that.oldInfo.id) { // 编辑
           that.categoryForm.id = that.oldInfo.id;
           that.categoryForm.name = that.oldInfo.name;
           that.categoryForm.fireSystemId = that.oldInfo.fireSystemId;
           that.categoryForm.remarks = that.oldInfo.remarks;
           that.categoryForm.isSupportSendDown = that.oldInfo.isSupportSendDown+'';
           that.categoryForm.isRelationChild = that.oldInfo.isRelationChild+'';
           that.categoryForm.hasAnalog = that.oldInfo.hasAnalog + ''
           var monitorType = that.oldInfo.monitorType;
           if (monitorType == '1,2') {
               that.categoryForm.isHighRisk = '1';
               that.categoryForm.isKeyUnit = '1';
           } else if (monitorType == '1') {
               that.categoryForm.isHighRisk = '0';
               that.categoryForm.isKeyUnit = '1';
           } else if (monitorType == '2') {
               that.categoryForm.isHighRisk = '1';
               that.categoryForm.isKeyUnit = '0';
           } else {
               that.categoryForm.isHighRisk = '0';
               that.categoryForm.isKeyUnit = '0';
           }
           var icon = JSON.parse(that.oldInfo.icon);
           icon.icon ? $.each(icon.icon.split(','), (index,url) => {
               that.listPicture.push({
                    name:'list_'+index,
                    url: url
               });
           }):''

           icon.detailIcon ? $.each(icon.detailIcon.split(','), (index,url) => {
               that.detailPicture.push({
                    name: 'detail_'+index,
                    url: url
               });
           }):''

           var categoryStatusesStr = that.oldInfo.categoryStatuses;
           for (var i = 0; i < categoryStatusesStr.length; i++) {
                if (categoryStatusesStr[i].fcfsStatus == 10) {
                    that.categoryForm.alarm_name = categoryStatusesStr[i].fcfsStatusName;
                    categoryStatusesStr[i].fcfsStatusUrl ? $.each(categoryStatusesStr[i].fcfsStatusUrl.split(','), (index,url) => {
                        that.alarmPicList.push({
                         name: categoryStatusesStr[i].fcfsStatusName + index,
                         url:url
                        })
                     }) : ''
                } else if (categoryStatusesStr[i].fcfsStatus == 20) {
                    that.categoryForm.fault_name = categoryStatusesStr[i].fcfsStatusName;
                    categoryStatusesStr[i].fcfsStatusUrl ? $.each(categoryStatusesStr[i].fcfsStatusUrl.split(','), (index,url) => {
                        that.faultPicList.push({
                         name: categoryStatusesStr[i].fcfsStatusName + index,
                         url:url
                        })
                     }) : ''
                } else if (categoryStatusesStr[i].fcfsStatus == 30) {
                    that.categoryForm.shield_name = categoryStatusesStr[i].fcfsStatusName;
                    categoryStatusesStr[i].fcfsStatusUrl ? $.each(categoryStatusesStr[i].fcfsStatusUrl.split(','), (index,url) => {
                        that.shieldPicList.push({
                         name: categoryStatusesStr[i].fcfsStatusName + index,
                         url:url
                        })
                     }) : ''
                } else if (categoryStatusesStr[i].fcfsStatus == 40) {
                    that.categoryForm.linkage_name = categoryStatusesStr[i].fcfsStatusName;
                    categoryStatusesStr[i].fcfsStatusUrl ? $.each(categoryStatusesStr[i].fcfsStatusUrl.split(','), (index,url) => {
                        that.linkagepicList.push({
                         name: categoryStatusesStr[i].fcfsStatusName + index,
                         url:url
                        })
                     }) : ''
                } else if (categoryStatusesStr[i].fcfsStatus == 0) {
                    that.categoryForm.normal_name = categoryStatusesStr[i].fcfsStatusName;
                    categoryStatusesStr[i].fcfsStatusUrl ? $.each(categoryStatusesStr[i].fcfsStatusUrl.split(','), (index,url) => {
                        that.normalPicList.push({
                         name: categoryStatusesStr[i].fcfsStatusName + index,
                         url:url
                        })
                     }) : ''
                } else {}
           }
        }
     },
     data() {
          return {
               isParent:true,
               options:[],
               Analogs:[{
                    value: '0',
                    name: '常规探测器',
               },{
                    value: '1',
                    name: '模拟量探测器',
               },{
                    value: '2',
                    name: '常规探测器含有模拟量数据',
               }],
               categoryForm: {
                    id:'',
                    name:'',
                    fireSystemId:'',
                    hasAnalog: '',
                    isSupportSendDown:'',
                    isRelationChild:'',
                    isHighRisk:'',
                    isKeyUnit: '',
                    alarm_name:'报警',
                    fault_name:'故障',
                    remarks:'',
                    normal_name:'正常',
                    linkage_name: '联动',
                    shield_name:'屏蔽',
               },
               alarmPicList:[],
               faultPicList:[],
               shieldPicList:[],
               linkagepicList:[],
               normalPicList:[],
               listPicture: [],
               detailPicture:[],
               qiniuData:{//上传图片携带的参数
                token : "",
                key : "",
               },
               categoryFormRules: {
                  name: [{ 
                      required: true, message: '请输入名称', trigger: 'blur' 
                  }],
                  fireSystemId: [{
                    required: true,message: '请选择所属消防系统', trigger: 'change'
                  }],
                  alarm_name:[{
                    required: true,message: '请输入报警状态子名称', trigger: 'blur'
                  }],
                  fault_name: [{
                    required: true, message: '请输入故障状态子名称', trigger: 'blur'
                  }],
                  shield_name: [{
                    required: true, message: '请输入屏蔽状态子名称', trigger: 'blur'
                  }],
                  normal_name: [{
                    required: true, message: '请输入正常状态子名称',    trigger: 'blur'
                  }],
                  linkage_name: [{
                    required: true,message: '请输入联动状态子名称', trigger: 'blur'
                  }]
               }
          }
     },
     methods: {
        getToken(){  //上传之前获取 token
            qnToken({}).then((result) => {
                this.qiniuData.token= result.data;
            });
        },
        /*下拉框筛选*/
        changeItem(selVal) {
            var self = this;
            self.categoryForm.fireSystemId = selVal;
         },
        changeAnalog(setVal) {
          var self = this;
          self.categoryForm.hasAnalog = setVal;
        },
        beforeAvatarUpload(file) {//重命名和校验
            var fielLocal = file.name.split(".");
            var fielType = "." + fielLocal[fielLocal.length-1];
            var fielLocalName = fielLocal[0];
            this.qiniuData.key = 'ilink_'+new Date().getTime()+fielType;
            const isJPG = file.type === "image/jpeg";
            const isPNG = file.type === "image/png";
            const isLt20M = file.size / 1024 / 1024 < 20;
            if (!isJPG && !isPNG) {
                this.$message.error("图片只能是 JPG/PNG 格式!");
                return false;
            }
            if (!isLt20M) {
                this.$message.error("图片大小不能超过 20MB!");
                return false;
            }
        },
        handleAvatarSuccess: function(res, file, fileList,flag) {//上传成功
           switch(flag) {
               case 1:
                  this.alarmPicList = fileList;
                  break;
               case 2:
                   this.faultPicList = fileList;
                   break;
               case 3:
                   this.shieldPicList = fileList;
                   break;
               case 4:
                   this.linkagepicList = fileList;
                   break;
               case 5:
                   this.normalPicList = fileList;
                   break;
               case 6:
                   this.listPicture = fileList;
                   break;
               case 7:
                   this.detailPicture = fileList;
                   break;
               default:
                   break;
            }
        },
        handleRemovePic: function(file, fileList,flag) {
            switch(flag) {
               case 1:
                  this.alarmPicList = fileList;
                  break;
               case 2:
                   this.faultPicList = fileList;
                   break;
               case 3:
                   this.shieldPicList = fileList;
                   break;
               case 4:
                   this.linkagepicList = fileList;
                   break;
               case 5:
                   this.normalPicList = fileList;
                   break;
               case 6:
                   this.listPicture = fileList;
                   break;
               case 7:
                   this.detailPicture = fileList;
                   break;
               default:
                   break;
          }
        },
        handleError: function(res) {
            this.$message({
                message: "上传失败",
                duration: 2000,
                type: "warning"
            });
        },
        /*保存数据*/
        saveCategoryInfo(formName) {
          var self = this;
                      // 阻止事件冒泡
            event.stopPropagation();

            self.$refs[formName].validate((valid) => {
               if (valid) {
                    var params = self.categoryForm;
                    var icon = {
                         icon: util.ilinkArrHandle.getqiniuPicUrlArr(self.listPicture).toString(),
                         detailIcon: util.ilinkArrHandle.getqiniuPicUrlArr(self.detailPicture).toString()
                    };  //列表和详情图片\
                    var categoryStatusesStr = [{
                         fcfsStatus: 10,
                         fcfsStatusName: self.categoryForm.alarm_name,
                         fcfsStatusUrl: util.ilinkArrHandle.getqiniuPicUrlArr(self.alarmPicList).toString()
                    },{
                         fcfsStatus: 20,
                         fcfsStatusName: self.categoryForm.fault_name,
                         fcfsStatusUrl: util.ilinkArrHandle.getqiniuPicUrlArr(self.faultPicList).toString()
                    },{
                         fcfsStatus: 30,
                         fcfsStatusName: self.categoryForm.shield_name,
                         fcfsStatusUrl: util.ilinkArrHandle.getqiniuPicUrlArr(self.shieldPicList).toString()
                    },{
                         fcfsStatus: 40,
                         fcfsStatusName: self.categoryForm.linkage_name,
                         fcfsStatusUrl: util.ilinkArrHandle.getqiniuPicUrlArr(self.linkagepicList).toString()
                    },{
                         fcfsStatus: 0,
                         fcfsStatusName: self.categoryForm.normal_name,
                         fcfsStatusUrl: util.ilinkArrHandle.getqiniuPicUrlArr(self.normalPicList).toString()
                    }];
                    var monitorType;
                    if (self.categoryForm.isKeyUnit == 1 && self.categoryForm.isHighRisk == 1) {
                         monitorType = "1,2";
                    } else if (self.categoryForm.isKeyUnit == 0 && self.categoryForm.isHighRisk == 1) {
                         monitorType = "2";
                    } else if (self.categoryForm.isKeyUnit == 1 && self.categoryForm.isHighRisk == 0) {
                         monitorType = "1";
                    } else {
                         monitorType = "";
                    }
                    if (self.parentId) {
                      params.fireSystemId = self.fireSystemId;
                    }
                    var paramList = {
                         id:params.id,
                         name: params.name,
                         fireSystemId: params.fireSystemId,
                         hasAnalog:params.hasAnalog,
                         isRelationChild:(params.isRelationChild==false?'0':params.isRelationChild),
                         isSupportSendDown:(params.isSupportSendDown==false?'0':params.isSupportSendDown),
                         isTop:1,
                         monitorType:monitorType,
                         name:params.name,
                         remarks:params.remarks,
                         icon: JSON.stringify(icon),
                         categoryStatusesStr:JSON.stringify(categoryStatusesStr)
                    };
                    if(self.parentId) {
                      paramList.parentId = self.parentId;
                      paramList.isTop = 0;
                    }
                    updateFireCtlCategory(paramList).then(res => {
                        if(res.status === 200) {
                            self.$message({
                                message: '保存成功！',
                                type: 'success'
                            });
                            self.closeFun(true);
                        } else {
                            self.$message({
                                message: res.info,
                                type: 'warning'
                            })
                        }
                    });
               } else {
                    return false;
               }
            });
        }
     }
}
</script>